package com.tx.filter;

import com.tx.exception.VerificationCodeException;
import com.tx.handler.MyAuthenticationFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class VerificationCodeFilter extends OncePerRequestFilter {

    @Autowired
    private MyAuthenticationFailHandler myAuthenticationFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        //不是登录请求跳过
        if (!"/login".equals(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            try{
                verificationCode(httpServletRequest);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }catch (VerificationCodeException e){
                myAuthenticationFailHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }

        }

    }


    public void verificationCode(HttpServletRequest request) throws VerificationCodeException {
        //获取用户提交的验证码
        String captcha = request.getParameter("captcha");
        //获取系统中的验证码
        HttpSession session = request.getSession();
        String systemCaptcha = (String) session.getAttribute("rightCode");

        //不管正确失败都删除验证码
        if (!StringUtils.isEmpty(systemCaptcha)) {
            session.removeAttribute("rightCode");
        }

        //校验不通过，抛出异常
        if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(systemCaptcha) || !captcha.equals(systemCaptcha)){
            throw new VerificationCodeException();
        }

    }


}
